import React from "react";
import BaseComponent from "@/BaseComponent";
import { Route, Link, Switch, Redirect } from "react-router-dom";

import { homeRoute, loginRoute, notFoundRoute } from "@routes/";
import AuthRoute from "@components/AuthRoute";
import { connect } from "react-redux";
import { Button } from "antd";

import jwt_decode from "jwt-decode";

class App extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    const { pathname } = this.props.history.location;
    const token = this.props.userInfo
      ? this.props.userInfo.get("usertoken")
      : "";
    if (pathname === "/login") {
      if (token) {
        return <Redirect to="/home" />;
      }
    } else if (token) {
      const decoded = jwt_decode(token);
      const currentTime = Date.now() / 1000; // 由毫秒转成秒
      if (decoded.exp < currentTime) {
        alert("登录超时，请重新登录");
        localStorage.removeItem("usertoken");
        return <Redirect to="/login" />;
      }
    }

    return (
      <div>
        <nav>
          <Button type="primary">
            <Link to={homeRoute.path}>后台管理页面</Link>
          </Button>
          <Button type="primary">
            <Link to={loginRoute.path}>登陆页面</Link>
          </Button>
          <Button type="primary">
            <Link to={notFoundRoute.path}>404页面</Link>
          </Button>
        </nav>
        <Switch>
          <AuthRoute {...homeRoute} />
          <Route path={loginRoute.path} component={loginRoute.component} />
          <Route
            path={notFoundRoute.path}
            component={notFoundRoute.component}
          />
          <Redirect exact to="/home" from="/" />
        </Switch>
      </div>
    );
  }
}
const mapStateToProps = (state) => ({
  userInfo: state.userReducer.get("userInfo"),
});

export default connect(mapStateToProps)(App);
